/**
 * Project oo_thread
 */


#include "../include/RegistGetusername.h"
#include "../include/MySQLConnector.h"
#include "../include/TLVmsg.h"
#include <ctime>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
using std::endl;
using std::cout;
enum TaskType{
    TASK_LOGIN_SECTION1 = 1, 
    TASK_LOGIN_SECTION1_RESP_OK,
    TASK_LOGIN_SECTION1_RESP_ERROR,
    TASK_LOGIN_SECTION2,
    TASK_LOGIN_SECTION2_RESP_OK,
    TASK_LOGIN_SECTION2_RESP_ERROR,
    TASK_TYPE_REGISTER1,
    TASK_TYPE_REGISTER1_RESP_OK,
    TASK_TYPE_REGISTER1_RESP_ERROR,
    TASK_TYPE_GEGISTER2,
    TASK_TYPE_REGISTER2_RESP_OK
};   

/**
 * RegisterTask implementation
 */
RegisterGetusername::RegisterGetusername(const string msg, TcpConnectionPtr conn)
:_msg(msg)
,_conn(conn)
{

}
string RegisterGetusername::GetRandomSalt(int length)
{
      int flag, i;
    char* salt;
    srand((unsigned) time(NULL ));
    if ((salt = (char*) malloc(length)) == NULL )  {
        printf("malloc failed!flag:14\n");
        return NULL ;
    }
    for (i = 0; i < length+1; i++)  {
        flag = rand() % 3;
        switch (flag)  {
            case 0:  salt[i] = 'A' + rand() % 26;  break;
            case 1:  salt[i] = 'a' + rand() % 26;  break;
            case 2:  salt[i] = '0' + rand() % 10;  break;
            default:  salt[i] = 'x';  break;
        }
    }
    salt[length] = '\0';
    string _salt(salt);
    return _salt;
}

/**
 * @return void
 */
void RegisterGetusername::process() {
    // cout << "RegisterTask.cpp 28 process(),msg = " << _msg << endl;

    //handle msg
    cout << "RegisterGetUsername handle msg" << endl;
    sleep(1);
    // string sql = "select * from user where name = '" + _msg + "'";
    MySQLConnector* mysqlconn = MySQLConnector::getInstance();
    string sql = "select * from user where name = '" + _msg + "'";
    LOG_WARN("forbit combining sql string, please conrrect later!!");
    cout << "sql = " << sql << endl;
    mysqlconn->query(sql);
    if(mysqlconn->hasResult())
    {
    cout << "RegisterGetusername.cpp 78, process(), already hasResult" << endl;
    mysqlconn->showResult();
    _conn->sendtoLoop(TASK_TYPE_REGISTER1_RESP_ERROR
                      ,"username has existed");
    }
    else
    {
    //生成盐值，发送给客户端
    string salt = GetRandomSalt(8);
    cout << "salt = " << salt << endl;
    _conn->sendtoLoop(TASK_TYPE_REGISTER1_RESP_OK
                      ,salt);
    }
}
